# -*- coding: utf-8 -*-
import json
import time
import hashlib
import logging
import requests
from django.conf import settings

from common.cache import redis_cache
from common.transaction.model import *
from common.utils.exceptions import ParamError, ServerError
from common.withdraw import check_daily_risk
from common.withdraw.db import withdraw_success_action, withdraw_failed_action
from common.transaction.model import Withdraw

_LOGGER = logging.getLogger('alipay')

_GATEWAY = 'http://www.qijipay.com/apiWithdraw/'

APP_CONF = {
    '100106': {
        'API_KEY': 'WsGhAzUJZdqjTjwY',
    },
    '100107': {
        'API_KEY': 'zTtfthiqZpVakEaO',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def create_bank_order(list):
    app_id = "100107"
    data = {
        "id": app_id,
        "key": _get_api_key(app_id),
    }
    data['data'] = list
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_GATEWAY, data=json.dumps(data), headers=headers, timeout=3)
    _LOGGER.info("bankcard_withdraw create rsp: %s", response.text)
    res_dict = json.loads(response.text)
    return res_dict['result_code']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def _verify_notify_sign(data):
    app_id = "100107"
    key = _get_api_key(app_id)
    sign = data['sign']
    item = Withdraw.query.filter(Withdraw.id == int(data['code_id'])).first()
    updated_info = json.loads(item.extend)
    bardbank_num = updated_info['info']['no']
    bank_name = updated_info['info']['bankname']
    s = '{}|{}|{}|{}|{}|{}|{}|{}|{}'.format(
        data['business_num'], key, data['code_id'], data['user_name'].encode('utf8'), data['user_name'].encode('utf8'),
        bardbank_num, data['money'], bank_name.encode('utf8'), settings.BANK_EXCHANGE_CALLBACK_URL,
    ).decode('utf8')
    _LOGGER.info("bankcard_withdraw sign str: %s ", s)
    calculated_sign = generate_sign(s)
    if sign != calculated_sign:
        _LOGGER.info("bankcard_withdraw sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % data)


# SUCCESS
def check_bankcard_withdraw_notify(request):
    data = request.POST.dict()
    _LOGGER.info('Auto trans bankcard, notify_data : %s ', data)
    _verify_notify_sign(data)
    order_id = data['code_id']
    trade_status = int(data['status'])
    if not order_id:
        _LOGGER.error("bankcard_withdraw fatal error, data: %s" % data)
        raise ParamError('bankcard_withdraw event does not contain valid order ID')

    amount = float(data['money'])
    trade_no = data['code_id']
    if trade_status == 1:
        succ = withdraw_success_action(order_id, amount, trade_no, payer_no='bankcard')
        if succ:
            _LOGGER.info('Auto trans bankcard, check_bankcard_withdraw_notify_sign succ')
            check_daily_risk(float(amount))
    else:
        withdraw_failed_action(order_id, amount, trade_status,
                               trade_status, trade_status, trade_no)
